const app = getApp()
const db = wx.cloud.database();

let filePath = null;
let topic = '';
let content = '';
let title = '';
let years = null;
let month = null;
let day = null;
let imgOrVideo1 = true;
let imgOrVideo2 = false;
Page({

  /**
   * 页面的初始数据
   */
  data: {
    topicText: '',
    postContent: '',
    tempUrl: '',
    tempvideoUrl: '',

    // 声明一个tempObject存放用户个人中心的游戏数据
    UserGameInfo: {},
  },

  // 获取当前用户信息
  getUserGameInfo(){
    db.collection("userInfo").where({
      _openid: app.currentUserOpenid
    }).get().then(res=>{
      this.setData({
        UserGameInfo: res.data[0]
      })
    })
  },

  // 图片和视频 上传/删除按钮点击事件
  cloudFile(filename,imgpath){
    wx.showLoading({
      title: '上传中...'
    })
    wx.cloud.uploadFile({
      cloudPath: filename+".jpg",
      filePath: imgpath
    }).then(res=>{
      // console.log("uploadFile res",res);
      filePath = res.fileID
      this.setData({
        hidetext: "block",
        hideimg: "none",
        tempUrl: res.fileID
      })
    })
    wx.hideLoading()
  },

  cloudFile2(filename,Videopath){
    wx.showLoading({
      title: '上传中...'
    })
    wx.cloud.uploadFile({
      cloudPath: filename+".mp4",
      filePath: Videopath
    }).then(res=>{
      filePath = res.fileID
      this.setData({
        hidevideo: "block",
        hideimg: "none",
        tempvideoUrl: res.fileID,
      })
    })
    wx.hideLoading()
  },

  // 上传图片/视频
  shangchuan(){
    wx.showModal({
      title: '提示',
      content: '请选择需要上传图片或者视频',
      cancelText: '视频',
      confirmText: '图片',
      cancelColor: '#5495e6',
      confirmColor: '#58bc58',
      success: (res)=> {
        // 用户点击图片
        if (res.confirm) {
          imgOrVideo1 = true
          imgOrVideo2 = false
          wx.chooseImage({
            count: 1,
            success: res2 => {
              filePath = res2.tempFilePaths[0] + ""  //获得图片的临时地址
              let fileName = Date.now();   // 给上传到存储里的图片一个以时间戳定义的名字
              this.cloudFile(fileName,filePath)
            }
          })
        } else if (res.cancel) {
          // 用户点击视频
          imgOrVideo1 = false
          imgOrVideo2 = true
          wx.chooseVideo({
            sourceType: ['album','camera'],
            maxDuration: 60,
            camera: 'back',
            success: res3 => {
              filePath = res3.tempFilePath + "" 
              let fileName = Date.now();  
              this.cloudFile2(fileName,filePath)
            }
          })
        }
      }
    })
  },

  getNowTime(){
    let NowTime = new Date()
    years = NowTime.getFullYear()
    month = NowTime.getMonth() + 1
    day = NowTime.getDate()
    return `${years}-${month}-${day}`
  },

  // 造一个将图片/视频的在存储中的地址上传到集合表里的函数
  onloadFilesToColl(topic,content,title){
    db.collection("publishPosts").add({
      data:{
        avatarUrl: this.data.UserGameInfo.avatarUrl,
        nickName: this.data.UserGameInfo.nickName,
        stage: this.data.UserGameInfo.stage.stageText,
        wdfImgUrl: filePath,
        title: title,
        inpTopic: topic,
        postContent: content,
        hits: Math.round(50 + Math.random()*200),
        comment: 0,
        publishTime: this.getNowTime(),
        wxkey: Math.random()*150401 + Math.random()*123125,
        imgOrVideo1: imgOrVideo1,
        imgOrVideo2: imgOrVideo2,
        comments: [],
      }
    }).then(()=>{
      this.data.wdfImgArr = []
      this.onLoad()
      console.log("图片已上传");
    })
  },

  reset(){
    this.setData({
      topicText: "",
      postContent: "",
      tempUrl: "",
      tempvideoUrl: "",
      hidetext: "none",
      hideimg: "block",
      hidevideo: "none"
    })
  },

  // 用户点击确定————提交表单
  postSubmit(res){
    if (this.data.tempvideoUrl || this.data.tempUrl) {
      this.setData({
        topicText: "",
        postContent: "",
        titleText: "",
        tempUrl: "",
        tempvideoUrl: "",
        hidetext: "none",
        hideimg: "block",
        hidevideo: "none"
      })
      topic = res.detail.value.topic
      content = res.detail.value.content
      title = res.detail.value.title
      this.onloadFilesToColl(topic,content,title)
      wx.showToast({
        title: '发布成功',
      })
      setTimeout(
        ()=>{
          wx.switchTab({
            url: '../community/community',
          })
        },1000
      )
    }else{
      wx.showToast({
        title: '发布失败',
        icon: 'error',
      })
    }
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.getUserGameInfo()
  },

  // 返回社区页面按钮
  backCom() {
    wx.switchTab({
      url: '../../pages/community/community',
    })
  },
})